<template>
    <div class="app-container home">
      <el-row :gutter="20">
        <el-col :sm="24" :lg="24">
          <b>我的抖音粉丝数</b>
  
          <!-- 上月 / 当前月 / 下月 控制按钮 -->
          <div style="margin: 15px 0; text-align: center">
            <el-button
              size="small"
              @click="goToPreviousMonth"
              :disabled="isAtMinMonth"
              icon="el-icon-arrow-left"
            >
              上月
            </el-button>
  
            <span style="margin: 0 15px; font-size: 16px; font-weight: bold; color: #333">
              {{ currentMonth }}
            </span>
  
            <el-button
              size="small"
              @click="goToNextMonth"
              :disabled="isAtMaxMonth"
            >
              下月
              <i class="el-icon-arrow-right el-icon--right"></i>
            </el-button>
          </div>
  
          <!-- 图表容器 -->
          <div class="chart-container">
            <div ref="chart2" class="echarts-box"></div>
          </div>
        </el-col>
      </el-row>
      <el-divider />
    </div>
  </template>
  
  <script>
  import * as echarts from 'echarts';
  import { getDouyinData } from "@/api/cd/custom/douyin.js";
  
  export default {
    name: "Index",
    data() {
      return {
        version: "1.0.0",
        lineData: [],
        xdata: [],
        chartInstance: null,
        currentMonth: this.formatDateToYYYYMM(new Date()) // 当前显示的月份
      };
    },
    computed: {
      // 判断是否已到最大月份（当前月）
      isAtMaxMonth() {
        const now = new Date();
        const current = this.parseDateFromYYYYMM(this.currentMonth);
        return (
          current.getFullYear() === now.getFullYear() &&
          current.getMonth() === now.getMonth()
        );
      },
      // 判断是否已到最小月份（可自定义，如 2024-01）
      isAtMinMonth() {
        const current = this.parseDateFromYYYYMM(this.currentMonth);
        const minDate = new Date(2024, 0); // 最早查 2024年1月
        return current <= minDate;
      }
    },
    mounted() {
      // 首次加载当前月数据
      this.fetchDataAndRender();
  
      // 监听窗口 resize
      window.addEventListener('resize', this.handleResize);
    },
    beforeDestroy() {
      // 组件销毁时清理
      window.removeEventListener('resize', this.handleResize);
      if (this.chartInstance) {
        this.chartInstance.dispose();
      }
    },
    methods: {
      /**
       * 将 Date 对象格式化为 yyyy-mm 字符串
       */
      formatDateToYYYYMM(date) {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        return `${year}-${month}`;
      },
  
      /**
       * 将 yyyy-mm 字符串解析为 Date 对象
       */
      parseDateFromYYYYMM(dateStr) {
        const [year, month] = dateStr.split('-').map(Number);
        return new Date(year, month - 1); // 注意：月份从 0 开始
      },
  
      /**
       * 跳转到上月
       */
      goToPreviousMonth() {
        const date = this.parseDateFromYYYYMM(this.currentMonth);
        date.setMonth(date.getMonth() - 1);
        const newMonth = this.formatDateToYYYYMM(date);
  
        // 边界判断：不能早于 2025-01
        const minDate = new Date(2025, 0);
        if (date < minDate) {
          this.$message.info('已到达最早查询月份');
          return;
        }
  
        this.currentMonth = newMonth;
        this.fetchDataAndRender();
      },
  
      /**
       * 跳转到下月
       */
      goToNextMonth() {
        const date = this.parseDateFromYYYYMM(this.currentMonth);
        date.setMonth(date.getMonth() + 1);
        const newMonth = this.formatDateToYYYYMM(date);
  
        // 边界判断：不能超过当前月
        const now = new Date();
        const maxDate = new Date(now.getFullYear(), now.getMonth());
        if (date > maxDate) {
          this.$message.info('不能查看未来月份');
          return;
        }
  
        this.currentMonth = newMonth;
        this.fetchDataAndRender();
      },
  
      /**
       * 封装：获取数据并渲染图表
       */
      fetchDataAndRender() {
        getDouyinData(this.currentMonth)
          .then(response => {
            const { ydata, xdata } = response.data;
            this.lineData = Array.isArray(ydata) ? ydata : [];
            this.xdata = Array.isArray(xdata) ? xdata : [];
            this.getLineChart();
          })
          .catch(error => {
            console.error('获取抖音数据失败：', error);
            this.$message({ type: 'error', message: '数据加载失败，请稍后重试' });
            // 可选：清空数据或保留旧数据
            this.lineData = [];
            this.xdata = [];
            this.getLineChart();
          });
      },
  
      /**
       * 根据数据动态计算 Y 轴的 min, max, interval
       */
      calculateYAxis(data) {
        if (!data || data.length === 0) {
          return { min: 0, max: 100, interval: 10 };
        }
  
        const maxValue = Math.max(...data);
        const minValue = Math.min(...data);
  
        if (maxValue === minValue) {
          const offset = 50;
          return {
            min: Math.max(0, minValue - offset),
            max: minValue + offset,
            interval: this.calculateNiceInterval(offset / 2)
          };
        }
  
        const range = maxValue - minValue;
        const padding = range * 0.2;
  
        let yAxisMin = Math.floor(minValue - padding);
        let yAxisMax = Math.ceil(maxValue + padding);
  
        if (yAxisMin < 0) yAxisMin = 0;
  
        const rawInterval = (yAxisMax - yAxisMin) / 6;
        const interval = this.calculateNiceInterval(rawInterval);
  
        return { min: yAxisMin, max: yAxisMax, interval };
      },
  
      /**
       * 计算“美观”的刻度间隔（1, 2, 5, 10, 25, 50...）
       */
      calculateNiceInterval(interval) {
        if (interval <= 0) return 1;
  
        const exp = Math.floor(Math.log10(interval));
        const mantissa = interval / Math.pow(10, exp);
  
        let niceMantissa;
        if (mantissa <= 1) niceMantissa = 1;
        else if (mantissa <= 2) niceMantissa = 2;
        else if (mantissa <= 5) niceMantissa = 5;
        else niceMantissa = 10;
  
        return niceMantissa * Math.pow(10, exp);
      },
  
      /**
       * 初始化或更新 ECharts 折线图
       */
      getLineChart() {
        const { min, max, interval } = this.calculateYAxis(this.lineData);
  
        const option = {
          title: {
            text: '当月粉丝趋势图',
            left: 'center',
            textStyle: {
              fontSize: 16,
              fontWeight: 'bold',
              color: '#333'
            }
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'line',
              lineStyle: { color: '#ccc' }
            },
            formatter: params => params[0].name + '<br/>粉丝数: ' + params[0].value
          },
          legend: { data: ['粉丝数'], top: '10%', left: 'center' },
          xAxis: {
            type: 'category',
            data: this.xdata,
            name: '时间',
            nameLocation: 'middle',
            nameGap: 30,
            axisLabel: { rotate: 45, fontSize: 12, color: '#666' }
          },
          yAxis: {
            type: 'value',
            name: '粉丝数',
            nameLocation: 'middle',
            nameGap: 40,
            min,
            max,
            interval,
            splitLine: {
              show: true,
              lineStyle: { color: ['#eee'], type: 'dashed' }
            },
            axisLabel: { fontSize: 12, color: '#666' }
          },
          series: [
            {
              name: '粉丝数',
              data: this.lineData,
              type: 'line',
              smooth: true,
              symbol: 'circle',
              symbolSize: 8,
              label: { show: true, position: 'top', textStyle: { fontSize: 14 } },
              lineStyle: { width: 2, color: '#4CAF50' },
              itemStyle: { color: '#4CAF50', borderColor: '#fff', borderWidth: 2 },
              areaStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: 'rgba(76, 175, 80, 0.3)' },
                  { offset: 1, color: 'rgba(76, 175, 80, 0)' }
                ])
              }
            }
          ],
          backgroundColor: '#fff',
          grid: { left: '10%', right: '10%', bottom: '15%', top: '20%', containLabel: true }
        };
  
        // 销毁旧实例
        if (this.chartInstance) {
          this.chartInstance.dispose();
        }
  
        // 初始化图表
        this.chartInstance = echarts.init(this.$refs.chart2);
        this.chartInstance.setOption(option);
        this.chartInstance.resize();
      },
  
      /**
       * 窗口大小变化时，图表自适应
       */
      handleResize() {
        if (this.chartInstance) {
          this.chartInstance.resize();
        }
      }
    }
  };
  </script>
  
  <style scoped lang="scss">
  .home {
    font-family: "open sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
    font-size: 13px;
    color: #676a6c;
    overflow-x: hidden;
  
    b {
      font-weight: 700;
    }
  
    h2 {
      margin-top: 10px;
      font-size: 26px;
      font-weight: 100;
    }
  
    p {
      margin-top: 10px;
    }
  
    ul {
      list-style-type: none;
      padding: 0;
    }
  }
  
  .chart-container {
    width: 100%;
    height: 400px;
    position: relative;
    margin-top: 20px;
  }
  
  .echarts-box {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
  }
  </style>